const express = require("express");
const mongoose = require("mongoose");

// 引入路由文件
const usersRouter = require("./routes/users");
const bannersRouter = require("./routes/banners");

// 创建express服务
const app = express();

// 链接mongodb
const uri = "mongodb://127.0.0.1:27017/maizuo";
mongoose
  .connect(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => {
    console.log("数据库链接成功");
  })
  .catch(err => {
    console.log("数据库链接失败", err);
  });

// 中间件处理
app.use(express.static("public"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use((req, res, next) => {
  res.set("Access-Control-Allow-Origin", "*");
  res.set("Access-Control-Allow-Headers", "content-type");
  res.set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE");
  next();
});

// 路由
app.use("/api", [usersRouter, bannersRouter]);

app.listen(3000);
